/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.battleship.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author jmunoz
 */
@WebServlet(name = "HomeServlet", urlPatterns = {"/HomeServlet"})
public class HomeServlet extends BaseServlet {

    static final String ATTRIBUTE_STATUS = "status";

    /**
     * Displays the existing messages and offer the option to send a new one.
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws IOException {
        resp.setContentType("text/html");
        PrintWriter out = resp.getWriter();

        out.print("<html><body>");
        out.print("<head>");
        out.println("<meta http-equiv=\"refresh\" content=\"5\" >");
        out.print("  <title>Battleship GCM Home</title>");
        out.print("  <link rel='icon' href='icon.png'/>");
        out.print("</head>");
        String status = (String) req.getAttribute(ATTRIBUTE_STATUS);
        if (status != null) {
            out.print(status);
        }
        List<String> devices = Datastore.getDevices();
        if (devices.isEmpty()) {
            out.print("<h2>No players registered!</h2>");
        } else {
            out.print("<h2>" + devices.size() + " player(s) registered!</h2>");
            for (int i = 0; i < devices.size(); i++) {
                out.print("<h5>Player " + i + " id: " + devices.get(i) + "</h5>");
            }
            out.print("<form name='form' method='POST' action='sendAll'>");
            out.print("<input type='submit' value='Send Message' />");
            out.print("</form>");
        }
        out.print("</body></html>");
        resp.setStatus(HttpServletResponse.SC_OK);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws IOException {
        doGet(req, resp);
    }
}